<script setup lang="ts">
const props = defineProps<{
  tripId?: string,
  receiverId?: string,
  userAlias: string,
}>()
const onClickLeft = () => history.back();
// let useAlias:Ref<string>=ref('')
const msg: Ref<string> = ref('')
const left = ['base-msg', 'left-msg']
const right = ['base-msg', 'right-msg']

let messageList: Ref<MessageVO[]> = ref([])
let load: any
onMounted(async function () {
  load = showLoadingToast({duration: 0, message: '加载中...'})
  let userId: string | null = null
  await cFetch<User>('/account/api/verifyToken', {
    auth: true,
    defaultOpts: {
      method: 'POST',
    }
  }).then(res => {
    userId = res.data[0].id
    // useAlias.value=res.data[0].useralias
  }).catch(err => {
    console.log(err)
    userId = null
  })
  if (!userId) return
  cFetch<NoticeVO>('/notice/api/list', {
    auth: true,
    defaultOpts: {
      method: 'POST',
      body: {
        receiverId: props.receiverId ? props.receiverId : null,
        tripId: props.tripId ? props.tripId : null,
      }
    }
  }).then((res) => {
    // console.log(res)
    res.data.forEach(item => {
      userId === item.receiverId ? messageList.value.push(new MessageVO(left, item.message)) : messageList.value.push(new MessageVO(right, item.message))
    })
    load.close()
  })
  webSocketStore().getWS()?.setMsgCallback(function (e: MessageEvent) {
    let t = JSON.parse(e.data) as any
    t.receiverId === userId ? messageList.value.push(new MessageVO(left, t.message)) : messageList.value.push(new MessageVO(right, t.message))
  })
})
onUnmounted(function () {
  if (load) load.close()
  //恢复设置
  webSocketStore().getWS()?.setMsgCallback(function (e: MessageEvent) {
    const ms = messageStore()
    ms.addMsg(e.data)
    showToast({
      message: '您有一条新的消息',
      duration: 2500,
    })
    // console.log(e.data)
  })
})

const scrollableDiv = ref();
const scrollToBottom = () => {
  scrollableDiv.value.scrollTop = scrollableDiv.value.scrollHeight;
};
watch(messageList.value, () => {
  setTimeout(() => {
    scrollToBottom()
  }, 20);
});

function sendMsg() {
  msg.value=msg.value.trimEnd()
  if(!msg.value){
    showToast('不能发送空的消息！')
    return
  }
  let msgJSON = {
    receiverId: props.receiverId ? props.receiverId : null,
    tripId: props.tripId ? props.tripId : null,
    message: msg.value,
  }
  let str = JSON.stringify(msgJSON);
  if (webSocketStore().getWS()?.sendMessage(str)) {
    messageList.value.push(new MessageVO(right, msgJSON.message))
    setTimeout(function () {
      msg.value = ''
    }, 100)
  } else {
    showToast('重连中……')
    // showNotify('连接错误')
  }

}
</script>

<template>
  <div style="display:flex;flex-direction: column;position: relative;height: 100vh;overflow: auto;">

    <header>
      <van-nav-bar
          :title="props.userAlias"
          left-text="返回"
          left-arrow
          @click-left="onClickLeft"
      />
    </header>

    <main>
      <div class="msg" ref="scrollableDiv">
        <span :class="item.pattern" v-for="item in messageList">
          {{ item.value }}
        </span>
      </div>
    </main>

    <footer>
      <van-cell-group inset class="chat-input">
        <van-field
            style="background-color: #e8e8e8;"
            v-model="msg"
            size="normal"
            type="textarea"
            :autosize="{maxHeight:40,minHeight:40,}"
            maxlength="150"
            show-word-limit
        >
          <template #button>
            <van-button size="small" type="success" @click="sendMsg">发送</van-button>
          </template>
        </van-field>
      </van-cell-group>
    </footer>

  </div>

</template>

<style scoped>
header {
  position: relative;
}

main {
  position: relative;
  flex: 1;
  overflow: auto;
  background-color: whitesmoke;
  padding-bottom: 104px;
}

footer {
  position: fixed;
  width: 100vw;
  bottom: 0;
  padding: 10px 0;
  background-color: #aeaeae;
}

.chat-input {
  position: relative;
  border: #d5d5d5 groove 1px;
}

.msg {
  height: 100%;
  overflow: auto;
  display: flex;
  flex-direction: column;
  position: relative;

}

.base-msg {
  border-radius: 10px;
  padding: 10px;
  margin: 13px 13px 0;
  max-width: 80%;
  width: fit-content;
  word-break: break-word;
}

.base-msg:last-child {
  margin-bottom: 13px;
}

.left-msg {
  background-color: #b8bfc6;
  margin-right: auto;
  position: relative;
}

.right-msg {
  background-color: #34f334;
  position: relative;
  margin-left: auto;
}
</style>